<?php

namespace xinsheng;

//use catcher\base\CatchRequest as Request;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\api\model\Order as customsOrder;
use catchAdmin\customs\model\XsRefund;
use catchAdmin\externalGoods\model\XinshengNotify;
use GuzzleHttp\Exception\RequestException;
use houniao\api\v1\Goods;
use think\facade\Db;
use think\Request;
use catcher\CatchResponse;
use houniao\tools\Params;
use think\Exception;
use think\facade\Log;

class Notify
{

//    protected $apiUrl = "https://uwebgatetest.hnapay.com/webgate/unifiedAPI.htm";
//    protected $public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTBlxr2F/cqm+amrmYHNpl5OEftqKfSi4QrqjtJreWk8gBXxl7ctkRwIp8EIn+gFMnxWSu6dP/cc9sl+FR5bQOKhTbIEJotkLa8vDE2waz7VYLpFnS5nCuzakfQvK3lzu3vzad0jzS5XuTLBJMDNuXDCueiRHN1jEXviiEWevXdQIDAQAB";

    protected $apiUrl = "https://uwebgate.hnapay.com/webgate/unifiedAPI.htm";
    protected $public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJFkdpM39EbL36SwGUi6LBpXE9kVfX1z4r7NZkJUArJPGkblCs1gW919eAchOZhKOP9eBGAc6KTK0qArujjb+bg69Xl3sqJq0xZJBR1SJbLFI/rV7p0J92crC9ymiGsECM+7DkZS8UXLZeO1aSt59KTgnpfyOX7s4XjMnOS6MbPQIDAQAB";
    protected $private_key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANMGXGvYX9yqb5qauZgc2mXk4R+2op9KLhCuqO0mt5aTyAFfGXty2RHAinwQif6AUyfFZK7p0/9xz2yX4VHltA4qFNsgQmi2Qtry8MTbBrPtVgukWdLmcK7NqR9C8reXO7e/Np3SPNLle5MsEkwM25cMK56JEc3WMRe+KIRZ69d1AgMBAAECgYBTSW1suyeKplIKCQs7OBgSozUfGSwyBksMFoNhpihLa+RCdlBOYtO9p+qAcN6l7evkBIpqZqtfZIHjcEZj1m8reIHHBnuv/sKGXWPvMBKqckenwNnqUzlj4X8hvFtkbcqXLGdyYoicW+P5+P8zHmYRom+izd5FO9281zXa4UK6gQJBAOquqD84B1VnNq2xopaaJvxaL4c5IOinkfRWShttANCpt1D0t1cs+7WPq9sdFZ4cyHYomxuC4knqJh1E/WzCVqUCQQDmMZH8+6sgqOrgsECw6w0KdUci/XgzT/DRS/3MFMeRv7ygEtdlyvyxRirEArsjQgDg3IBLo9TxBUdygPhgXnSRAkEAtp95r9By7IOoKhw8cMO+qMuphqnvMP0NeD0Z6CO36ajYTXhRn9YSfiQyUQ1eAC9X05MfuJXucCR0ynwgVd0ZPQJAdYaRdow3TrFvWdAi9zDKs7A05ZRrrib+WJ1nsq5ZRfySnVeBSaNdaFTeuLx8NwAX2rY5emTm7zc2xys5pFoVQQJAUPrxmTbELDTF1by6POX/IT3iSeClzOx+M05Yd4sgXtALPjYt0VMLtnsfmt9qMEjhk0Q95wgdmeHsBHxno5qGfQ==";
    protected $newpay_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmVh2/xldLXhVU/mNT57m95uw0Hr0Pdl4pUyM2xV509LqLYTbLduCqqnuMTJUq7Irv8SsKfVqB7zKggxFyjmIfeeyTbhMDJkWZ20xRhv+rSw3ZBQD/Hbn+cxhi4FZ3gc+jUSI1pIsPrlvRK7E5DyWLa/RvZYiQfW/XYI4c1Mb29QIDAQAB";
    protected $merCode = '10000000863';//商户代码
    protected $versionNo= '2.0';
    protected $signType = "2";

    public function notify(Request $request){

//        $data = '{"head":{"serCode":"101018","merCode":"10000000357","orderId":"3316465520020608","merDate":"20210317","merTime":"100137","versionNo":"2.0","signType":"1"},"content":{"responseCode":"0000","responseDesc":"请求处理成功","payTransactionNo":"1022103170954030269","merOrderId":"20210317095442409112","checkOrg":"2","checkOrgOrderNo":"4200000901202103173885445476","resultCode":"2","resultMsg":"报关成功","completeTime":"20210317100137"},"sign":"HYNfsQO8c42cH3q8bnnzZ8nP05qxuIgsfPRqYYlmn45tK33uM7Is/BfM1phWSV3sBvus25kDWQlK/2TN+8MPDwwNdC+Md3S3L2DBx+0dCCzItFV1vMTcC8hl1WCcBoYcqIfT4HRZQiHuDsGdMSgvKR/UM5Drj1tgvg/sX4UcB1U="}';
//        $data = json_decode($data,true)['content'];
//        $url = "https://tyj.qekj.net/appinterface/Workwx/test";
//        $_content = $this->sendNotice($url,$data);
//        dump($_content);die();

        //return response('Internal Server Error', 500);

        $data = $request->post('msg');
        Log::error(json_encode($data));
//        Log::record(json_encode($data));
//        Log::write(json_encode($data));

//        $data = 'eyJoZWFkIjp7InNlckNvZGUiOiIxMDEwMTgiLCJtZXJDb2RlIjoiMTAwMDAwMDAzODEiLCJvcmRlcklkIjoiNzA2MTc5NjUwNjY4ODM1NjI2MDYiLCJtZXJEYXRlIjoiMjAyMzA2MTMiLCJtZXJUaW1lIjoiMTYyMTAwIiwidmVyc2lvbk5vIjoiMi4wIiwic2lnblR5cGUiOiIyIn0sImNvbnRlbnQiOnsicmVzcG9uc2VDb2RlIjoiMDAwMCIsInJlc3BvbnNlRGVzYyI6Iuivt+axguWkhOeQhuaIkOWKnyIsInBheVRyYW5zYWN0aW9uTm8iOiIxMDIyMzA2MTMxNjE4MDM3MDEwIiwibWVyT3JkZXJJZCI6IjE2MTc0NTYxMDIwODM5OTk3Njc1IiwiY2hlY2tPcmciOiIyIiwiY2hlY2tPcmdPcmRlck5vIjoiNTEyMDIzMDYxMzIyMDAxNDQzNDkxNDMxMTgzNTQ3IiwicmVzdWx0Q29kZSI6IjIiLCJyZXN1bHRNc2ciOiLmiqXlhbPmiJDlip8iLCJjb21wbGV0ZVRpbWUiOiIyMDIzMDYxMzE2MjEwMCJ9LCJzaWduIjoiMDgxMGE3ZmJmMzEwYzA4YTlmNzU1ZTA3YzAxZjZmODAifQ==';
//        $data = 'eyJoZWFkIjp7InNlckNvZGUiOiIxMDEwMDgiLCJtZXJDb2RlIjoiMTAwMDAwMDAzODE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ODE);


//        $data = '{"head":{"serCode":"101018","merCode":"10000000357","orderId":"3316465520020608","merDate":"20210317","merTime":"100137","versionNo":"2.0","signType":"1"},"content":{"responseCode":"0000","responseDesc":"请求处理成功","payTransactionNo":"1022103170954030269","merOrderId":"20210317095442409112","checkOrg":"2","checkOrgOrderNo":"4200000901202103173885445476","resultCode":"2","resultMsg":"报关成功","completeTime":"20210317100137"},"sign":"HYNfsQO8c42cH3q8bnnzZ8nP05qxuIgsfPRqYYlmn45tK33uM7Is/BfM1phWSV3sBvus25kDWQlK/2TN+8MPDwwNdC+Md3S3L2DBx+0dCCzItFV1vMTcC8hl1WCcBoYcqIfT4HRZQiHuDsGdMSgvKR/UM5Drj1tgvg/sX4UcB1U="}';
//        $data = '{"head":{"serCode":"101005","merCode":"10000000381","orderId":"1686624730517555","merDate":"20230613","merTime":"105210","versionNo":"2.0","signType":"2"},"content":{"merOrderId":"168662473497355552","displayName":"柯洁牛肉汤","goodsName":"牛肉粉丝汤","goodsCount":1,"orderAmount":1,"orderCurrencyCode":"CNY","tradeType":"0002","payType":"4","orgCode":"alipay","payCurrencyCode":"CNY","settleCurrencyCode":"CNY","shareFlag":"0","returnUrl":"http://localhost:8080/gatewayTest/notify","noticeUrl":"http://localhost:8080/gatewayTest/notify"},"sign":"5421c7719eb2c99176c93c554bde527d"}';
//        $data = json_decode($data,true);

        //$this->checkSign($data,$data['sign']);

        if(empty($data) || !array_key_exists('sign',$data)){
            Log::error(json_encode('参数错误'));
            die(json_encode([
                'code'=>-1,
                'msg'=>'参数错误'
            ],JSON_UNESCAPED_UNICODE));
        }

        //后期维护到配置中
        if('10000000889' == $data['head']['merCode']){
            $this->public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIxqxcsyOxtdUgYFh49Xbs+wFjpRMYmiyUxxkvq+uHziUWIAOoW0bBnonWx7I358/zQItd7c4rFlidFpoS2XVG/OBTWGVfu8LjSLeSv650ldnDXYSBRtYlI6PqpjHeYxr0vUjiVFnc9yfT0yXiFBHGCDBOKH20P/1LNlvUxexmgwIDAQAB';
        }elseif ('10000000890' == $data['head']['merCode']){
            $this->public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnB5TpxPqMZwgarw1xNSTxb2nGeBxlCJ8WwInbeNs52s7w6qBmZJVJN456WoRWeI4mf2WZ7PfVmE+iY+LLjAQ+YZ07A6AI0FtKGIQM4lCtgbjYbi/yCrqwG+Y1odNZkUD+0zHwsJnLEovUx/Ah03Z2wEaY6pidaR+v9ERK/XmiwIDAQAB';
        }elseif ('10000000938' == $data['head']['merCode']){//广电悦采
            $this->public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsrshGKOzARNQ65zlZ4izJPUGYTQOINg++2WOZ//ECkmnJqPinSs4ou4NXqnOSBs255JHLO5Xx3d/OXLZ03bg5tUWYSLBkCAAmcBljyMFFOD6hUN8QBd9NAEbspw5uXegqDO/ZAtENwg8bY5at5feagUTEP710jsBgBFkGPnjiXwIDAQAB';
        }elseif ('10000000937' == $data['head']['merCode']){//丝路电商馆
            $this->public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTDxEfIEiCZ6DF4xxF45Q2tuz+YXIfneLct4dGrVeyvfJ0SGSF44LVjFbnn2/Zgo6+eOBPtqkk5Xhz0t6UM6owXNBsQ0+f54p8vIDixfDFB1EPYeGrNAD7yneZnRQrVk5C58n6FjRyz8DVa4C94mGf1MPQvt43inEP5K/Sj6hCZQIDAQAB';
        }elseif ('10000001001' == $data['head']['merCode']){//扬州文商
            $this->public_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkLJf6Rh/iQ7VO6jqNzD5AneS++Jh1kkjtbdflXeyBnh70AFGsHgLa70P8TvUfywKqgkY5Vq8+psw7ROhZjyqMqC+rz+M6zpf43R2lvTuCAP3wbbtBdP25QHqIgVTXAVvDcX+YNn+YY2bbB7/IUXurhEOUmEKUOC5YT5cUMSG1XwIDAQAB';
        }
        else{//默认 863 东九
            $this->public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJFkdpM39EbL36SwGUi6LBpXE9kVfX1z4r7NZkJUArJPGkblCs1gW919eAchOZhKOP9eBGAc6KTK0qArujjb+bg69Xl3sqJq0xZJBR1SJbLFI/rV7p0J92crC9ymiGsECM+7DkZS8UXLZeO1aSt59KTgnpfyOX7s4XjMnOS6MbPQIDAQAB";
        }

        if(!$this->checkSign($data,$data['sign'])){
            Log::error(json_encode('sign错误'));
            die(json_encode([
                'code'=>-1,
                'msg'=>'sign错误'
            ],JSON_UNESCAPED_UNICODE));
        }

        //成功了这里
        //Log::write('ok了');
       // Log::write(json_encode($data));
        //Log::error(json_encode('到这里了'));

        $pk =  event('xinshengNotify',$data)[0];

        Db::startTrans();
        if($data['content']['responseCode'] == '0000'){
            try {
                switch ($data['head']['serCode']){
                    case "101008"://代表支付回调
                        //预付卡回掉的时候，OrderID不相同 普通微信支付不影响
                        if('10' == $data['content']['payType']){//预付卡
                            sleep(5);
                            $model = (new XsOrder)->where('merOrderId',$data['content']['merOrderId'])->find();
                        }else{
                            $model = (new XsOrder)->where('orderId',$data['head']['orderId'])->find();
                        }

//                        $model->xs_status = $data['content']['status'];
                        $model->status = $data['content']['status'];
                        $model->completeTime = $data['content']['completeTime'];
//                        $model->push_status = '已付款';
//                        $model->realPayment =  number_format($data['content']['payAmount'] / 100 ,2) ;
                        $model->payAmount =  number_format($data['content']['payAmount'] / 100 ,2) ;
                        $model->save();
                        break;
                    case "101018":
                        $model = (new XsOrder)->where('merOrderId',$data['content']['merOrderId'])->find();
                        $model->_customsApply_data = $data['content'];
                        $model->checkOrg = $data['content']['checkOrg'];
                        $model->checkOrgOrderNo = $data['content']['checkOrgOrderNo'];
                        $model->save();
                        break;
                    case "101009"://退款回掉接口
                        $model = (new XsRefund)->where('orderId',$data['head']['orderId'])->find();
                        $model->status = $data['content']['status'];
                        $model->responseDesc = $data['content']['responseDesc'];
                        $model->completeTime = $data['content']['completeTime'];
                        $model->_notify_data = $data['content'];
                        $model->save();
                        break;
                    default:
                        break;
                }

                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                //Log::error($exception->getMessage());
                //die("error");
            }
        }

        if("101008" == $data['head']['serCode']){
            $url = $model->toNoticeUrl;
        }elseif ('101018' == $data['head']['serCode']){
            $url = $model->toNoticeUrl2;
        }

//        $url = "https://tyj.qekj.net/appinterface/Workwx/test";

        Log::error('失败失败' . $model->toNoticeUrl);

        //发通知
        //$_content = $this->sendNotice($model->toNotifyUrl,$data);

        $_notice_data = [
            'data'=>$data['content'],
            'sign'=>$this->_makeSign($data['content'])
        ];

        $result = $this->sendNotice($url,$_notice_data);
        $xsNotifyModel = new XinshengNotify();
        $xsNotifyData =  $xsNotifyModel->find($pk);
        $xsNotifyData->save([
            'to_notice_url'=>$url,
            'to_notice_response_code'=>$result['code'],
            'to_notice_response_data'=>$result['data'],
            'tenant_id'=>$model->tenant_id,
        ]);

        //return response('Internal Server Error', 500);
        if($result['result'])
            die("SUCCESS");
        else
            return response('Internal Server Error', 500);
    }

    protected function _makeSign($data){

       return md5(stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE)));
    }

    //检验sign
    protected function checkSign($data,$request_sign)
    {
        $headContent = [
            'head'=>$data['head'],
            'content'=>$data['content']
        ];

//        dd($headcontent);

        $headcontent1 = md5(stripslashes(json_encode($headContent,JSON_UNESCAPED_UNICODE)));

//        $private_key = $this->private_key;
//        $private_key = chunk_split($private_key,64,"\n");
//        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n{$private_key}-----END RSA PRIVATE KEY-----\n";
//        openssl_sign( $headcontent1 ,$encry, $private_key,OPENSSL_ALGO_SHA256);
//        dd(base64_encode($encry));

        $makeSign = md5($headcontent1 . $this->public_key);

        if ($makeSign == $request_sign) {
            return true;
        } else {
            return false;
        }
    }

    protected function sendNotice($url,$data){
        $options = [];
        try {
            $client = new \GuzzleHttp\Client();
            if(!empty($data)) {
                $options['form_params']=$data;

//                $options['body']= json_encode($data);
                $options['headers']= [
//                    'Content-Type' => 'application/json',
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ];
                $options['timeout'] = 10;//20秒
            }
            /*print_r($this->options);
            die;*/
            $response = $client->request('POST', $url, $options);
            $content = $response->getBody()->getContents();

            $to_notice_response_code = $response->getStatusCode();

            if(is_string($content) && trim($content) === 'SUCCESS')
                return ['result'=>true,'code'=>$to_notice_response_code,'data'=> 'SUCCESS'];
            else
                return ['result'=>false,'code'=>$to_notice_response_code,'data'=> json_encode($content)];
        }catch (RequestException $e){
            if(method_exists($e->getResponse(),'getBody'))
                return ['result'=>false,'code'=>$e->getCode(),'data'=> json_encode($e->getResponse()->getBody()->getContents())];
            else
                return ['result'=>false,'code'=>$e->getCode(),'data'=> json_encode([])];
        }
    }
}